# coding:utf8
from sqlalchemy import or_

from appserver import db_store
from models.entity.model_base import ModelBase
from models.entity.device import Device

"""
巡检项管理
"""


class PatrolManage(ModelBase):
    __tablename__ = "patrol_manage"
    __bind_key__ = "main"
    # 在链接过程中对应的值为2
    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    code = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'编号')
    content =  db_store.Column(db_store.String(64), nullable=False, comment=u'巡检项内容')
    device_type_id = db_store.Column(db_store.Integer, db_store.ForeignKey('device_types.id'))
    status = db_store.Column(db_store.Integer, nullable =False, comment=u'状态')    # 是否启用  0启用  1弃用

    def __repr__(self):
        return "<PatrolManage %s>" % self.content

    @staticmethod
    def get_patrol_manage_by_code(code):
        return PatrolManage.query.filter_by(code=code).first()

    @staticmethod
    def get_patrol_manage_by_device_id(device_id):
        the_device=Device.query.filter_by(id=device_id).first()
        return PatrolManage.query.filter_by(device_type_id = the_device.id).filter_by(status=0).all()
    
    @staticmethod
    def get_patrol_manage_by_device_type(device_type):
        return PatrolManage.query.filter_by(device_type_id= device_type).filter_by(status=0).all()
    
    @staticmethod
    def get_patrol_manage_all_by_device_type(device_type):
        return PatrolManage.query.filter_by(device_type_id=device_type).all()

    @staticmethod
    def search(query_word):
        search_list = PatrolManage.query.filter(
            or_(PatrolManage.code.like("%" + query_word + "%"), PatrolManage.content.like("%" + query_word + "%"),
                PatrolManage.status.like("%" + query_word + "%"))).all()

        tlist = []
        for item in search_list:
            tlist.append(item.to_dict())
        rdic = {
            "success": 1,
            "error_code": None,
            "error_msg": None,
            "data": tlist
        }
        return rdic
